<?php

namespace app\admin\controller;

use app\admin\library\DbLink;
use app\common\controller\Backend;
use think\Db;
use app\admin\controller\MwColumn as columnC;
use think\Exception;

/**
 * 主模块
 *
 * @icon fa fa-circle-o
 */
class MwModule extends Backend
{

    /**
     * MwModule模型对象
     * @var \app\admin\model\MwModule
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\MwModule;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     * @return string|\think\response\Json
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $projectId = $this->request->get('project_id');
            $where1['project_id']=$projectId;
            $list = $this->model
                ->with(['mwproject','mwconnection'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加模块，同时生成对应的数据库
     * @return mixed|\think\response\Json
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public  function add(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $params = $this->request->post()['row'];

            if(!isset($params['project_id']) || empty($params['project_id'])) return json(['code'=>0,'msg'=>'project_id错误']);
            if(!isset($params['connection_id']) || empty($params['connection_id'])) return json(['code'=>0,'msg'=>'connection_id错误']);
            if(!isset($params['name']) || empty($params['name'])) return json(['code'=>0,'msg'=>'name错误']);
            if(!isset($params['table_name']) || empty($params['table_name'])) return json(['code'=>0,'msg'=>'table_name错误']);
            //判断模块名在项目下唯一
            $info = $this->model->where(['project_id'=>$params['project_id'], 'name'=>$params['name']])->find();
            if ($info){
                return json(['code'=>0,'msg'=>'添加失败，模块名已存在']);
            }
            //获取模块连接数据
            $connection_model = new \app\admin\model\MwConnection();
            $connect_info = $connection_model->get($params['connection_id']);

            $connect = DbLink::Connect($connect_info['type'],$connect_info['host'],$connect_info['port'],$connect_info['user'],$connect_info['password'],$connect_info['database']);
            //获取表备注
            $table_status = DbLink::getTableStatus($connect,$params['table_name']);
            if (!empty($table_status['Comment'])){
                $params['comment'] = $table_status['Comment'];
            }else{
                $params['comment'] = '';
            }

            Db::startTrans();
            try {
                $this->model->save($params);
                $column = new columnC();
                $column->insertData($connect,$this->model->id, $params['table_name'], $connect_info['database']);
//                throw new Exception("自定义错误");
                //获取模块能力
                $capability_model = new \app\admin\model\MwModuleCapability();
                $capability_model->addBaseAll($this->model->id);

                Db::commit();
                return json(['code'=>1,'msg'=>'添加成功']);

            } catch (\Exception $e) {
                Db::rollback();
                return json(['code'=>0,'msg'=>'添加失败']);
            }
        }
        return $this->fetch();
    }
}
